package com.alvin.demo.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Tcp_Utils_Netty {

    public String sendMessage( String host , int port , String msg ) {
        EventLoopGroup group = new NioEventLoopGroup();
        ResultHandler resultHandler = new ResultHandler(msg);
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 500)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch){
                            ChannelPipeline pipeline=ch.pipeline();
                            //往pipeline链中添加自定义的handler(业务处理类)
                            pipeline.addLast(resultHandler);
                        }
                    });
            ChannelFuture cf = bootstrap.connect().sync();
            //8.关闭连接(异步非阻塞)
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            return "error" ;
        }finally {
            group.shutdownGracefully() ;
        }
        return resultHandler.getResultStr();
    }

    public static void main(String[] args){
        Tcp_Utils_Netty tcp_utils = new Tcp_Utils_Netty();
        String hexString = NumberUtils.longToHexString(Long.parseLong("179218272") , 8);
        String commandStr = hexString + " " + "03 FF 11";
        int count = 0 ;
        for (int i = 0 ; i < 100 ; i++ ){
            String result = tcp_utils.sendMessage("192.168.0.102", 8886, commandStr);
            System.out.println(result);
            if (result.length()!=71){
                count++ ;
            }
            System.out.println("=========================================================================");
        }
        System.out.println(count);
    }

}